package com.mqb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author mqb
 * @date 2021/3/31 16:56
 */
@Component
public class VerifyCodeFilter extends GenericFilterBean {

    private final String defaultLoginProcessingUrl = "/login";

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        // 判断当前请求是否为登录请求
        if ("POST".equalsIgnoreCase(req.getMethod()) && defaultLoginProcessingUrl.equals(req.getServletPath())) {
            // 校验验证码
            String code = request.getParameter("code");
            HttpSession session = req.getSession();
            if (session == null) {
                authenticationFailureHandler.onAuthenticationFailure(req,resp,new VerifyInvalidException("验证码错误"));
            }

            String codeInSession = (String) session.getAttribute("index_code");
            if (StringUtils.isEmpty(code)) {
                authenticationFailureHandler.onAuthenticationFailure(req,resp,new VerifyInvalidException("验证码不能为空"));
            }
            if (!codeInSession.equalsIgnoreCase(code)) {
                authenticationFailureHandler.onAuthenticationFailure(req,resp,new VerifyInvalidException("验证码错误"));
            }
        }
        chain.doFilter(req, resp);
    }
}
